程式碼:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>save.php</title>
</head>
<body>
<?php
header("Content-Type:text/html; charset=utf-8");
session_start();
$file = "formData.csv";
$content = "姓名,電話,生日,Email,地址\r\n".$_SESSION["name"].",".$_SESSION["tel"].",".$_SESSION["birthday"].",".$_SESSION["email"].",".$_SESSION["address"];
$fp=fopen($file,"w")
or exit ("檔案 $file 開啟錯誤<br/>");
//fwrite($fp, iconv('UTF-8', 'BIG5',$content)); //註1
//fwrite($fp, $content); //註2
//如果使用註2Excel會出現亂碼,excel 出現亂碼的原因是檔首無 BOM(https://en.wikipedia.org/wiki/Byte_order_mark)
//普通Txt檔可使用註2
//註1是另一種解法
if(fwrite($fp, "\xEF\xBB\xBF".$content) ){
print "寫入檔案 $file 成功<br/>";
}else{
print "寫入檔案 $file 錯誤<br/>";
}
fclose($fp);
?>
</body>
</html>
結果:
頁面
csv檔
參考資料:http://chiahan.logdown.com/posts/280868/web-php-export-csv-chinese-encoding-problem
解決PHP印出csv有亂碼